package com.ikas.ai.server.config.tdengine;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.logging.slf4j.Slf4jImpl;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @Description: tdEngine 数据源配置
 * @Author: qi.yilai
 * @Date: 2023/1/11 11:23
 * @Version: 1.0.0
 **/
@EnableConfigurationProperties(value = {TDEngineProperties.class})
@MapperScan(value = {"com.ikas.ai.server.module.*.tdDao"}, sqlSessionFactoryRef = "TDengineSqlSessionFactory")
@Slf4j
@Configuration
public class TDEngineConfig {

    private static final String DRIVER_CLASS_NAME = "com.taosdata.jdbc.rs.RestfulDriver";
    private static final String MAPPER_LOCATION = "classpath:mybatis/tdengine/mapper/*.xml";
    private static final String VALIDATE_QUERY = "select server_status()";
    private static final String TYPE_ALIASES_PACKAGE = "com.ikas.ai.server.module.*.model";

    @Autowired
    private TDEngineProperties tdEngineProperties;

    /**
     * 创建数据源
     *
     * @return
     * @throws Exception
     */
    @Bean(name = "TDengineDataSource")
    public DataSource tdengineDataSource() throws Exception {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(DRIVER_CLASS_NAME);
        dataSource.setUrl(tdEngineProperties.getHost());
        dataSource.setPassword(tdEngineProperties.getDbPassword());
        dataSource.setUsername(tdEngineProperties.getUserName());
        dataSource.setInitialSize(tdEngineProperties.getInitSize());
        dataSource.setMinIdle(tdEngineProperties.getMinIdleSize());
        dataSource.setMaxActive(tdEngineProperties.getMaxActiveSize());
        dataSource.setMaxWait(tdEngineProperties.getMaxWait());
        dataSource.setValidationQuery(VALIDATE_QUERY);
        log.info("初始化TDEngine数据源成功url:{}",tdEngineProperties.getHost());
        return dataSource;
    }

    /**
     * 创建事务管理器
     *
     * @param dataSource
     * @return
     */
    @Bean(name = "TDengineTransactionManager")
    public DataSourceTransactionManager tdengineTransactionManager(@Qualifier("TDengineDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * 创建session factory
     *
     * @param dataSource
     * @return
     * @throws Exception
     */
    @Bean(name = "TDengineSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("TDengineDataSource") DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        org.springframework.core.io.Resource[] resources = new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION);
        sessionFactory.setMapperLocations(resources);
        sessionFactory.setTypeAliasesPackage(TYPE_ALIASES_PACKAGE);
        sessionFactory.setConfiguration(createConfiguration());
        return sessionFactory.getObject();
    }

    /**
     * 创建 mybatis配置
     *
     * @return
     */
    private MybatisConfiguration createConfiguration() {
        MybatisConfiguration mybatisConfiguration = new MybatisConfiguration();
        mybatisConfiguration.setMapUnderscoreToCamelCase(true);
        mybatisConfiguration.setCallSettersOnNulls(true);
        mybatisConfiguration.setLogImpl(Slf4jImpl.class);
        return mybatisConfiguration;
    }

    @Bean("TDSqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("TDengineSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
